package com.finalBlog.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.jfinal.kit.PathKit;

/**
 * finalBlog
 *	
 * 类/接口信息描述:
 *
 * @author dengxc
 *
 */
@SuppressWarnings("rawtypes")
public class FileSearchTool {
	private String classpath = PathKit.getRootClassPath();
    private static final Logger log = Logger.getLogger(FileSearchTool.class);

    /**
     * 方法功能描述：获取指定包名下的Class 对象数组
     *
     * @param packagename 包名多个以英文逗号隔开
     * @return List<Class> Class 对象数组
     * 
     * @author dengxc
     * 
     */
    public List<Class> find(String packagename){
		List<Class> result = new ArrayList<Class>();
		
		if(StringUtils.isNotEmpty(packagename)){
			String pkgarr[] = null;
			if(packagename.indexOf(",")!=-1){
				pkgarr = packagename.split(",");
			}else{
				pkgarr = new String[1];
				pkgarr[0] = packagename;
			}
			for(String pkg:pkgarr){
				String packagepath = "";
				if(pkg.indexOf(".")!=-1){
					packagepath = pkg.replace(".", File.separator);
				}
				String basedir = classpath+File.separator+packagepath;
				log.info("扫描路径："+basedir);
				List<String> fileList = findFile(basedir, "class");
				for(String filename:fileList){
					try {
						Class cls = Class.forName(pkg+"."+filename);
						result.add(cls);
					} catch (ClassNotFoundException e) {
						log.error("类"+filename+"不存在！", e);
					}
				}
			}
		}else{
			log.warn("controller 包名 为空，无法绑定路由信息！");
		}
		return result;
	}
	public static List<String> findFile(String basepath,String patten){
		List<String> targets = new ArrayList<String>();
		File baseDir = new File(basepath);
		if(!baseDir.exists()||!baseDir.isDirectory()){
			log.error("the path "+basepath+" is not a dir!");
		}else{
			String[] files = baseDir.list();
			for(int i =0;i<files.length;i++){
				File current = new File(basepath+File.separator+files[i]);
				if(current.isDirectory()){
					//递归文件夹
					targets.addAll(findFile(current.getPath(), patten));
				}else{
					String filename  = current.getName();
					if(filename.endsWith(patten)){
						targets.add(filename.replace("."+patten, ""));
					}
				}
			}
		}
		return targets;
	}
}
